package com.icesoft.test.suppose;

import com.icesoft.base.manager.entity.system.SysOrg;
import com.icesoft.base.manager.helper.AuthUser;
import com.icesoft.base.manager.helper.UserPermission;
import com.icesoft.base.manager.security.config.ApiMatchAuthority;
import com.icesoft.base.manager.security.suppose.IUserDetailsService;
import com.icesoft.base.manager.service.system.SysOrgService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Collections;
import java.util.stream.Collectors;

@Slf4j
@Component
@AllArgsConstructor
public class SysUserDTOService implements IUserDetailsService {
    private PasswordEncoder passwordEncoder;
    private SysOrgService sysOrgService;

    @Override
    public UserDetails loadUserByPhone(String phone) throws UsernameNotFoundException {
        return getAuthUser(phone);
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        return getAuthUser(username);
    }

    private AuthUser getAuthUser(String username) {
        String password = passwordEncoder.encode("123456");
        System.err.println("临时账号密码------------------>" + password);
        UserPermission userPermission = new UserPermission(new ArrayList<>(), sysOrgService.findAll().stream().map(SysOrg::getId).collect(Collectors.toSet()));
        AuthUser user = new AuthUser(1, "超级管理员", 1, 1, username, password
                , Collections.singletonList(new ApiMatchAuthority("superAdmin", Collections.singletonList("/**"))));
        user.setPermission(userPermission);
        return user;
    }
}
